package com.ambow.utils;

import java.util.Iterator;
import java.util.List;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.jboss.logging.Logger;


public class BaseDAO {
	private static final Logger logger = Logger.getLogger(BaseDAO.class);
      /**
     * @param obj 添加数据
     * @return
     */
      public static boolean add(Object obj)
      {
        Session session=null;
        Transaction tran=null;
        boolean result=false;
        try
        {
            session=HibernateUtil.getSession();
           
            tran=session.beginTransaction();
            session.save(obj);
            tran.commit();
            result=true;
        }
        catch (Exception e)
        {
           if(tran!=null)
           {
               //事物回滚
               tran.rollback();
           }
        }
        finally
        {
            if(session!=null)
            {
                //关闭session
            	 HibernateUtil.clossSession();
            }
        }
        return result;
      }
      
      /**
     * @return 更新数据 
     * 参数为修改的主键id对象
     */
    public static boolean update(Object object)
      {
            Session session=null;
            Transaction tran=null;
            boolean result=false;
            try
            {
                session=HibernateUtil.getSession();
                tran=session.beginTransaction();
                session.update(object);
                tran.commit();
                result=true;
                if (logger.isDebugEnabled()) {
    				logger.debug("保存实体成功，");
    			}
    			
                
            }catch (Exception e)
            {
               if(tran!=null)
               {
                   //事物回滚
                   tran.rollback();
               }
            }
            finally
            {
                if(session!=null)
                {
                    //关闭session
                    HibernateUtil.clossSession();
                }
            }
            return result;
          }
         
      /**
     * @param c
     * @param id  查询一条数据根据主键的id号
     * @return
     */
      public static Object get(Class c,int id)
      {
            Session session=null;
            Object object=null;
            try
            {
                session=HibernateUtil.getSession();
                object=session.get(c,id);
            }
            catch (Exception e)
            {
            }
            finally
            {
                if(session!=null)
                {
                    //关闭session
                	 HibernateUtil.clossSession();
                }
            }
            return object;
      }

      /**
     * @param obj
     * @return 删除数据
     */
    public static boolean delete(Object obj)
      {
            Session session=null;
            Transaction tran=null;
            boolean result=false;
            try
            {
                session=HibernateUtil.getSession();
                tran=session.beginTransaction();
                session.delete(obj);
                tran.commit();
                result=true;
            }
            catch (Exception e)
            {
               if(tran!=null)
               {
                   //事物回滚
                   tran.rollback();
               }
            }
            finally
            {
                if(session!=null)
                {
                    //关闭session
                	 HibernateUtil.clossSession();
                }
            }
            return result;
      }
    
    /*
     * @param id
     * @return
     */
    public static boolean deleteById(Class c,Integer id) {
    	Session session = null;
    	Transaction tx = null;
    	boolean result = false;
    	try {
    		session = HibernateUtil.getSession();
    		tx = session.beginTransaction();
			Object obj = session.get(c.getName(), id);
			session.delete(obj);
			tx.commit();
			result = true;
		} catch (Exception e) {
			if(tx!=null) {
				tx.rollback();
			}
		}finally
        {
            if(session!=null)
            {
                HibernateUtil.clossSession();
            }
        }
    	return result;
    }

    /**
     * @param hql   hql语句
     * @return
     */
    public static Object getSingleByHql(String hql) {
    	Session session=null;
    	session = HibernateUtil.getSession();
    	return session.createQuery(hql).uniqueResult();
		
    }
    
    
    public static Object getSingleBySql(Class c,String sql) {
    	Session session=null;
    	session = HibernateUtil.getSession();
    	return session.createSQLQuery(sql).addEntity(c).uniqueResult();
		
    }
    /*
     * @param hql
     * @return
     */
    public static <T> List<T> queryAll(String hql){
    	List<T> list=new ArrayList<T>();
        Session session=null;
         try
          {
              session=HibernateUtil.getSession();
              Query query=session.createQuery(hql);
              list=query.list();
          }
          catch (Exception e)
          {
          }
          finally
          {
              if(session!=null)
              {
              	HibernateUtil.clossSession();
              }
          }
        return list;
    }
    
    
    public static <T> List<T> queryRandBySql(Class c,String sql){
    	List<T> list=new ArrayList<T>();
        Session session=null;
         try
          {
              session=HibernateUtil.getSession();
              Query query=session.createSQLQuery(sql).addEntity(c);
              list=query.list();
          }
          catch (Exception e)
          {
          }
          finally
          {
              if(session!=null)
              {
              	HibernateUtil.clossSession();
              }
          }
        return list;
    }
    /**
     * @param <T> 查询多条记录
     * @param hql  hql语句
     * @param param 参数数组
     * @return
     */
     @SuppressWarnings("unchecked")
    public static <T> List<T> query(String hql,String[] param)
      {

          List<T> list=new ArrayList<T>();
          Session session=null;
           try
            {
                session=HibernateUtil.getSession();
                Query query=session.createQuery(hql);
                if(param!=null)
                {
                    for(int i=0;i<param.length;i++)
                    {
                        query.setString(i,param[i]);    
                    }
                }
                list=query.list();
            }
            catch (Exception e)
            {
            }
            finally
            {
                if(session!=null)
                {
                	HibernateUtil.clossSession();
                }
            }
          return list;
      }
     
     /**
      * @param <T> 查询多条记录
      * @param sql  sql语句
      * @param param 参数数组
      * @return
      */
      @SuppressWarnings("unchecked")
     public static <T> List<T> queryBySql(Class c,String sql,String[] param)
       {

           List<T> list=new ArrayList<T>();
           Session session=null;
            try
             {
                 session=HibernateUtil.getSession();
                 Query query=session.createSQLQuery(sql).addEntity(c);
                 if(param!=null)
                 {
                     for(int i=0;i<param.length;i++)
                     {
                         query.setString(i,param[i]);    
                     }
                 }
                 list=query.list();
             }
             catch (Exception e)
             {
             }
             finally
             {
                 if(session!=null)
                 {
                 	HibernateUtil.clossSession();
                 }
             }
           return list;
       }
      /**
     * @param sql
     * @param param 查询单条记录
     * @return
     */
    public static Object queryOne(String hql,String[] param)
      {
          Object object=null;
          Session session=null;
           try
            {
                session=HibernateUtil.getSession();
                Query query=session.createQuery(hql);
                if(param!=null)
                {
                    for(int i=0;i<param.length;i++)
                    {
                        query.setString(i,param[i]);    
                    }
                    object=query.uniqueResult();
                }
            }
            catch (Exception e)
            {
            	e.printStackTrace();
            }
            finally
            {
                if(session!=null)
                {
                	HibernateUtil.clossSession();
                }
            }
          return object;
      }
    /**
     * @param <T>
     * @param sql
     * @param param
     * @param page
     * @param size
     * @return 实现分页查询
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> queryByPage(String sql,String[] param,int page,int size)
      {
          List<T> list=new ArrayList<T>();
          Session session=null;
           try
            {
                session=HibernateUtil.getSession();
                Query query=session.createQuery(sql);
                if(param!=null)
                {
                    for(int i=0;i<param.length;i++)
                    {
                        query.setString(i,param[i]);    
                    }
                }
                //筛选条数
                query.setFirstResult((page-1)*size);
                query.setMaxResults(size);
                list=query.list();
            }
            catch (Exception e)
            {
            }
            finally
            {
                if(session!=null)
                {
                	HibernateUtil.clossSession();
                }
            }
          return list;
      }
    /**
     * @param hql
     * @param pras
     * @return返回数据个数
     */
    public static int getCount(String hql, int[] pras) {
        int resu = 0;
        Session s = null;
        try {
            s = HibernateUtil.getSession();
            Query q = s.createQuery(hql);
            if (pras != null) {
                for (int i = 0; i < pras.length; i++) {
                    q.setInteger(i, pras[i]);
                }
            }
            resu = Integer.valueOf(q.iterate().next().toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (s != null)
            	HibernateUtil.clossSession();
        }
        return resu;
    }
    
  //分页查询
  	public static <T> PageResults<T> getPageByFetchedHql(String hql, String countHql,
  			int pageNo, int pageSize) {
  		PageResults<T> retValue = new PageResults<T>();
  		Query query = HibernateUtil.getSession().createQuery(hql);
  		int currentPage = pageNo > 1 ? pageNo : 1;
  		retValue.setCurrentPage(currentPage);
  		retValue.setPageSize(pageSize);
  		if (countHql == null) {
  			ScrollableResults results = query.scroll();
  			results.last();
  			retValue.setTotalCount(results.getRowNumber() + 1);// 设置总记录数
  		} else {
  			Long count = getCountByHql(countHql);
  			retValue.setTotalCount(count.intValue());
  		}
  		retValue.resetPageNo();
  		List<T> itemList = query.setFirstResult((currentPage - 1) * pageSize)
  				.setMaxResults(pageSize).list();
  		if (itemList == null) {
  			itemList = new ArrayList<T>();
  		}
  		retValue.setResults(itemList);

  		return retValue;
  	}
  	
  	//得到数据个数
  	public static Long getCountByHql(String hql) {
  		Query query = HibernateUtil.getSession().createQuery(hql);
  		return (Long) query.uniqueResult();
  	}
    
    /*
     * @param hql
     * @param param
     * @return
     */
	public static Integer updateByHql(String hql,String[] param) {
		Session session = null;
		Transaction tx = null;
		Integer m = null ;
		try {
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			Query query = session.createQuery(hql);
			for(int i=0;i<param.length;i++) {
				query.setString(i, param[i]);
			}
			m = query.executeUpdate();
			tx.commit();
		} catch (Exception e) {
			if(tx!=null) {
				tx.rollback();
			}
		}finally {
			if(session!=null) {
				HibernateUtil.clossSession();
			}
		}
		return m;
	}

    //总的页数--数据总数除于要分的页数
    public Integer getTotalPages(String hql){
    	Integer size = 5;
    	Integer totalPages = 0;
    	Integer total = 0;
    	Session session = null;
    	Transaction tran = null;
    	try {
			Query query = session.createQuery(hql);
			total = Integer.valueOf(query.iterate().next().toString());
			totalPages = total%size==0?total/size:total/size+1;
		}catch (Exception e) {
			if(tran!=null) {
				tran.rollback();
			}
		}finally {
			if(session!=null) {
				HibernateUtil.clossSession();
			}
		}
    	return totalPages;
    }
    //获取数据总条数
	public static int getConut(String hql) {
		Session session = null;
		Transaction tran = null;
		Integer count = 0;
		try {
			session = HibernateUtil.getSession();
			tran = session.beginTransaction();
			Query q = session.createQuery(hql);
			List list = q.list();
			String li = list.get(0).toString();
			count = Integer.parseInt(li);
		} catch (Exception e) {
			if(tran!=null) {
				tran.rollback();
			}
		}finally {
			if(session!=null) {
				HibernateUtil.clossSession();
			}
		}
		
		return count;
	}
    //查询限制的几条的记录
    public static <T> List<T> show(String hql ,Integer currentPage,Integer size){
    	//hql="select * from Product where label=? limit"+(currentPage-1)*size+","+size);
         Session session = HibernateUtil.getSession();
         //开启事物
         Transaction tran=session.beginTransaction();
         List<T> list=new ArrayList<T>();
		try {
			session = HibernateUtil.getSession();
			tran = session.beginTransaction();
			Query query=session.createQuery(hql);
	        list = query.list();
		} catch (Exception e) {
			if(tran!=null) {
				tran.rollback();
			}
		}finally {
			if(session!=null) {
				HibernateUtil.clossSession();
			}
		}
		return list;
    }
     

}